#include "PrismaticJoint.h"

CCScene* TestPrismaticJoint::scene()
{
	CCScene* pSc = CCScene::create();
	TestPrismaticJoint* layer = TestPrismaticJoint::create();
	pSc->addChild(layer);

	return pSc;
}

bool TestPrismaticJoint::init()
{
	BaseLayer::init();

	initJoint();

	scheduleUpdate();

	return true;
}

void TestPrismaticJoint::initJoint()
{
	b2Body* bodyA = NULL;
	{
		b2BodyDef bodyDef;
		bodyDef.type = b2_dynamicBody;
		bodyDef.position.Set(winSize.width/2/PTM_RATIO, winSize.height/2/PTM_RATIO);

		b2PolygonShape boxShape;
		boxShape.SetAsBox(2, 2);

		b2FixtureDef fixDef;
		fixDef.density = 1.0f;
		fixDef.friction = 0.3f;
		fixDef.restitution = 2.0f;
		fixDef.shape = &boxShape;

		bodyA = m_world->CreateBody(&bodyDef);
		bodyA->CreateFixture(&fixDef);
	}

	b2Body* bodyB = NULL;
	{
		b2BodyDef bodyDef;
		bodyDef.type = b2_dynamicBody;
		bodyDef.position.Set(winSize.width/2/ PTM_RATIO - 8, winSize.height/2/ PTM_RATIO);

		b2CircleShape cirShape;
		cirShape.m_radius = 1;

		b2FixtureDef fixDef;
		fixDef.density = 1.0f;
		fixDef.shape = &cirShape;

		bodyB = m_world->CreateBody(&bodyDef);
		bodyB->CreateFixture(&fixDef);;
	}

	b2PrismaticJointDef jointDef;
	b2Vec2 worldAxis(1.0f, 0.0f);
	jointDef.Initialize(bodyA, bodyB, bodyA->GetWorldCenter(), worldAxis);
	jointDef.lowerTranslation = -0.5f;
	jointDef.upperTranslation = 2.5f;
	jointDef.enableLimit = true;
	jointDef.motorSpeed = 0.0f;
	jointDef.maxMotorForce = 1.0f;
	b2PrismaticJoint* joint = (b2PrismaticJoint*)m_world->CreateJoint(&jointDef);
}

void TestPrismaticJoint::update(float dt)
{
	int32 velocityIterations = 8;
	int32 positionIterations = 1;

	m_world->Step(dt, velocityIterations, positionIterations);
}